#include "CalcCorrelations.h"

#include <ctime>
#include <time.h>
#include <sstream>

using namespace std;

// //
// // buildCorrelations
// //
// void CalcCorrelations::buildCorrelations
//      ( map< int, vector< CorrespondenceMatrix* > >& allCorrespondences, 
//        const vector< string >& image_seg_filename, 
//        const vector< string >& image_raw_filename,
//        const int start, const int stop, const vector< unsigned int >& inc,
//        const int dist_delta,
//        const string corrPrefix,
//        const vector< LabelType >& labelsToSkip,
//        bool writeBinary )
// {
//    //
//    //  Read in the slices
//    //
//    if( image_seg_filename.size() != image_raw_filename.size() )
//    {
//       for( unsigned int f = 0; f < image_seg_filename.size(); f++ )
//          cout << image_seg_filename[f] << endl ;
//       for( unsigned int f = 0; f < image_raw_filename.size(); f++ )
//          cout << image_raw_filename[f] << endl ;
//       cout << "ERROR: different numbers of raw and segmented files...  exiting" << endl;
//       exit(1);
//    }


//    //float sigma_size = 100;

//    /*
//    makeTestCorrespondences();
//    return 1;
//     */

//    //
//    //  loop over all the slices and calc the correlations
//    //
//    for( unsigned int i = start; i <= stop - inc[ inc.size() - 1]; i++ )
//    {
//       //
//       //  read in the segmented files
//       //
//       cout << "reading " << image_seg_filename[i] << endl ;
//       LabelImageReader::Pointer readImageA = LabelImageReader::New();
//       readImageA->SetFileName( image_seg_filename[i] );
//       readImageA->Update();
//       LabelImageType::Pointer labeled_image_A = readImageA->GetOutput();
//       //cout << labeled_image_A->GetLargestPossibleRegion() << endl;

//       //
//       //  read in the raw files
//       //
//       RawImageReader::Pointer readRawImageA = RawImageReader::New();
//       readRawImageA->SetFileName( image_raw_filename[i] );
//       readRawImageA->Update();
//       ScalarImageType::Pointer raw_image_A = readRawImageA->GetOutput();

//       //
//       //  extract all the regions from this slice
//       //
//       RegionList all_regions_A( labeled_image_A, raw_image_A, i,
//                                 labelsToSkip );

//       // keep track of all the correspondences
//       vector< CorrespondenceMatrix* > correspondenceMatrixList;

//       for( unsigned int ii = 0; ii < inc.size(); ii++ )
//       //for( unsigned int binc = i+1; binc <= i+inc; binc++ )
//       {
//          unsigned int binc = i + inc[ ii ];
//          if( binc == stop)
//             break;
//          cout << "comparing slice " << i << " to " << binc << endl ;

//          cout << "reading " << image_seg_filename[binc] << endl ;
//          LabelImageReader::Pointer readImageB = LabelImageReader::New();
//          readImageB->SetFileName( image_seg_filename[binc] );
//          readImageB->Update();
//          LabelImageType::Pointer labeled_image_B = readImageB->GetOutput();

//          RawImageReader::Pointer readRawImageB = RawImageReader::New();
//          readRawImageB->SetFileName( image_raw_filename[binc] );
//          readRawImageB->Update();
//          ScalarImageType::Pointer raw_image_B = readRawImageB->GetOutput();

//          //
//          // extract all regions in each image
//          //
//          RegionList all_regions_B( labeled_image_B, raw_image_B, binc, labelsToSkip );

//          // restrict calculations to regions within a threshold
//          cout << "dist_delta: " << dist_delta << endl ;
//          CorrespondenceMatrix* corrMatrix = 
//             new CorrespondenceMatrix ( 
//                    all_regions_A.compare( all_regions_B, dist_delta ) );

//          //
//          //  write out the correspondences as we go
//          //
//          if( writeBinary )
//             corrMatrix->writeBinary( corrPrefix );
//          else
//             corrMatrix->writeASCII( corrPrefix );

//          // get rid of correlations we dont want to put in the graph
//          corrMatrix->pruneCorrespondences();

//          correspondenceMatrixList.push_back( corrMatrix );

//       }

//       allCorrespondences[ i ] = correspondenceMatrixList;
//    }
// }

//
//  redCorrelations
//
void CalcCorrelations::readCorrelations
   ( map< int, vector< CorrespondenceMatrix* > >& allCorrespondences,
     const vector< string >& correlation_filenames,
     const int start, const int stop, const vector<unsigned int>& inc )
{

   /*
   // test correlation read/write
   CorrespondenceMatrix* corrMatrix = new CorrespondenceMatrix( correlation_filenames[0] );
   //corrMatrix->writeASCII( "asciitest" );
   corrMatrix->writeBinary( "binary" );
   cout << "done writing" << endl;
   CorrespondenceMatrix* bcm = new CorrespondenceMatrix( "binary000-001.csv" );
   bcm->writeASCII( "ascii" );
   exit(1);
   */

      map< int, vector< CorrespondenceMatrix* > >::iterator iter;
      for( unsigned int f = 0; f < correlation_filenames.size(); f++ )
      {
         // get the first two slices to see if we want to read this file
         int sliceA, sliceB = 0;
         CorrespondenceMatrix::getSlices( correlation_filenames[f], sliceA, sliceB );
         if( sliceA < start )
            continue;
         if( sliceB > stop )  // assuming all the matrices come in, in order
            return;

         // some timing
         //clock_t clock_start = clock();
         time_t clock_start, clock_end;
         time( &clock_start );

         // cout << "reading " << correlation_filenames[f] << endl ;
         CorrespondenceMatrix* corrMatrix = new CorrespondenceMatrix( correlation_filenames[f] );

         //int sliceA = corrMatrix->getSliceA();
         //int sliceB = corrMatrix->getSliceB();

         // lets only read in the matrices that we want!!!
         int sliceinc = sliceB - sliceA;

         // are we skipping slices?
         if( find( inc.begin(), inc.end(), sliceinc ) != inc.end() )
            // are we getting the right slices?
            if(  ( sliceA >= start ) && ( sliceB <= stop ) )
            {

               //
               // find the slice
               //
               iter = allCorrespondences.find( sliceA - start);

               //
               // if we dont have a correspondence for this slice, make one
               //
               if ( iter == allCorrespondences.end() )
               {
                  //if( allCorrespondeces[ sliceA ] )
                  vector< CorrespondenceMatrix* > cml;
                  cml.push_back( corrMatrix );
                  allCorrespondences[ sliceA - start ] = cml;
               }
               //
               //  otherwise, add it to the existing map
               //
               else // already in the map
               {
                  iter->second.push_back( corrMatrix );
               }

            }

         //int secs = (clock() - clock_start) / (double)CLOCKS_PER_SEC;
         // time( &clock_end );
         // int secs = difftime( clock_end, clock_start ); 
         // int mins = secs / 60;
         // stringstream time_string;
         // time_string << "time: " << secs << ", seconds, or " << mins << " minutes";
         // cout << "done reading " << correlation_filenames[f] 
         //    << " " << time_string.str() << endl ;

      }

      // debug :-P  - write out the files to see if we read them in
      // correctly
      /*
      bool debug = false;
      if( debug )
      {
         for( iter = allCorrespondences.begin(); iter!= allCorrespondences.end(); iter++ )
         {
            vector< CorrespondenceMatrix > cm = iter->second;
            for( unsigned int i = 0; i < cm.size(); i++ )
            {
               // debug :-P
               cm[i].write(
                     "/usr/sci/crcnsdata/elegansData/Biol5285_reconstruction/datav2/final_data/corrtest/");
            }

         }
      }
      */
}
